package com.polly.esphwevent.common.jwtutils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;


public class JwtTokenUtil {
    private String jwtSecret;
    private Long expiredTime;
    private String issuer;

    JwtTokenUtil(String issuer,String jwtSecret,Long expiredTime){
        this.issuer = issuer;
        this.jwtSecret = jwtSecret;
        this.expiredTime = expiredTime;
    }


    public String generateToken(String userId, Map<String, Object> claims) {
        final Date expirationDate = new Date(System.currentTimeMillis() + expiredTime * 1000);
        return generateToken(userId, expirationDate, claims);
    }

    public String generateToken(String userId, Date expiredDate, Map<String, Object> claims) {
        final Date createdDate = new Date();
        if (claims == null) {
            return Jwts.builder()
                    .setSubject(userId)
                    .setIssuer(issuer)
                    .setIssuedAt(createdDate)
                    .setExpiration(expiredDate)
                    .signWith(SignatureAlgorithm.HS512, this.jwtSecret)
                    .compact();
        } else {
            return Jwts.builder()
                    .setClaims(claims)
                    .setIssuer(issuer)
                    .setSubject(userId)
                    .setIssuedAt(createdDate)
                    .setExpiration(expiredDate)
                    .signWith(SignatureAlgorithm.HS512, this.jwtSecret)
                    .compact();
        }
    }


    public Boolean checkToken(String token) throws JwtException {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
            return true;
        } catch (JwtException e) {
            return false;
        }
    }

    public Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getClaimFromToken(token).getExpiration();
            return expiration.before(new Date());
        } catch (ExpiredJwtException expiredJwtException) {
            return true;
        }
    }

    public Claims getClaimFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtSecret)
                .parseClaimsJws(token)
                .getBody();
    }


}
